<template>
  <div class="question-detail">
    <div class="question">{{ question.question }}</div>
    <div class="answer" v-html="formattedAnswer"></div>
    <div class="actions">
      <el-button @click="regenerateAnswer">重新生成答案</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { marked } from 'marked'
import axios from 'axios'

const props = defineProps(['question'])
const answer = ref(props.question.answer)
const streaming = ref(false)

const formattedAnswer = computed(() => {
  return marked(answer.value || '')
})

const regenerateAnswer = async () => {
  streaming.value = true
  answer.value = ''
  
  const eventSource = new EventSource(`/api/questions/stream/${props.question.id}`)
  // let buffer = ""; // 用于累积数据块

  eventSource.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      console.log(data)

      const typeData = data[0]
      if (typeData.data === 'event:error\ndata:') {
        return
      }
      if (typeData.data === 'event:complete\ndata:') {
        return
      }
      answer.value += data[1].data
    } catch (error) {
      console.log(JSON.parse(error))
      answer.value += event.data[1].data
    }
};

  
  eventSource.onerror = (error) => {
    console.error('Stream error:', error)
    eventSource.close()
    streaming.value = false
  }
  
  eventSource.addEventListener('complete', () => {
    console.log('Stream completed')
    eventSource.close()
    streaming.value = false
  })
}
</script> 